<template>
	<!-- 自定义navbar组件【放在窗体外部，否则被content占据间距】 -->
	<CustomNavbar navTitle='密码登录' :isTitleStyle="true"></CustomNavbar>
	<view class="wrap">
		<view class="top"></view>
		<view class="content">
			<view class="title">欢迎登录</view>			
			<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
			<up-form :model="userForm" ref="userFormRef" :rules="rules">
				<up-form-item label="账号" prop="userName">
					<up-input v-model="userForm.userName" placeholder="请输入账号" clearable  prefixIcon="account-fill" />
				</up-form-item>
				<up-form-item label="密码" prop="userPwd" class="mb20">
					<up-input v-model="userForm.userPwd" placeholder="请输入密码" clearable  prefixIcon="lock" type="password" />
				</up-form-item>
			</up-form>
			<up-button class="mt20" type="primary" size="normal" text="提交" @tap="confirm"></up-button>
			<up-button class="mt20" size="normal" text="重置" @tap="handleReset"></up-button>
		</view>
	</view>
</template>
<script setup>  
	import { ref, reactive } from 'vue';
	import CustomNavbar from '@/components/CustomNavbar.vue'	
	
	import { userApi } from '@/utils/api.js'
	import { userInfoStore } from '@/store/userInfo.js'
	 
	//表单数据
	const userForm = reactive({
		userName: '',  
		userPwd: '',
	});  
	
	//表单引用
	const userFormRef = ref(null);  
	
	//校验规则  
	const rules = {  
		userName: [  
			{  
				required: true,  
				message: '请输入账号',  
				trigger: ['blur'],  
			},  
		],  
		userPwd: [
			{
				required: true,
				message: '请输入密码',
				trigger: ['blur'],
			}
		]
	};  
	
	//确定
	const confirm = ()=>{
		//表单验证
		userFormRef.value.validate().then(valid => {  
			if (valid) { //校验通过  
				userApi.login(userForm).then(res=>{
					if (res) {//表示后台验证通过
						setTimeout(function () {
							const store = userInfoStore()
							//更新全局登录信息
							store.token = res.token;
							store.userInfo = JSON.stringify(res.userInfo);
							//持久化缓存
							uni.setStorageSync("token",store.token)
							uni.setStorageSync("userInfo",store.userInfo)
							//跳转【我的】页
							uni.navigateTo({
								url: '/pages/my/index'
							})
						},200)
					}
				})
			}
		}) 
	} 
	//重置
	const handleReset = ()=>{
		this.$refs.userFormRef.resetFields()
		userFormRef.value.clearValidate(); //todo 清空内容
	}
</script>
<style lang="scss">
	.wrap {
		font-size: 28rpx;
		.content {
			width: 600rpx;
			margin: 80rpx auto 0;
			.title {
				text-align: left;
				font-size: 60rpx;
				font-weight: 500;
				margin-bottom: 100rpx;
			}
			.tips {
				color: $u-info;
				margin-bottom: 60rpx;
				margin-top: 8rpx;
				font-size: 12px;
			}
		}
	}
</style>